package com.joinway.framework.bean.utils;

import java.lang.reflect.Field;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import com.joinway.framework.bean.logging.annotation.LogIgnore;
import com.joinway.framework.bean.logging.annotation.LogMask;
import com.joinway.framework.bean.logging.type.LogMaskType;

public class MaskedReflectionToStringBuilder extends ReflectionToStringBuilder {

    public MaskedReflectionToStringBuilder(Object object, ToStringStyle style,
			StringBuffer buffer) {
		super(object, style, buffer);
	}

	public MaskedReflectionToStringBuilder(Object object, ToStringStyle style) {
		super(object, style);
	}

	public MaskedReflectionToStringBuilder(Object object) {
		super(object);
	}

	public <T> MaskedReflectionToStringBuilder(T object, ToStringStyle style,
			StringBuffer buffer, Class<? super T> reflectUpToClass,
			boolean outputTransients, boolean outputStatics) {
		super(object, style, buffer, reflectUpToClass, outputTransients, outputStatics);
	}

	@Override
    protected Object getValue(Field field) throws IllegalArgumentException, IllegalAccessException {
        Object value = super.getValue(field);


        do{
            // output null field by default
            if(value == null) break;
            
            LogIgnore ignore = field.getAnnotation(LogIgnore.class);
            if(ignore != null){
                value = "<ignored>";
                break;
            }
            
            LogMask ann = field.getAnnotation(LogMask.class);
            if(ann == null) break;
            
            if(LoggingHelper.isSimpleType(value.getClass())){
                // simple type mask as string
                if(ann.value() == LogMaskType.SimpleMask){
                    value = LoggingHelper.markString(String.valueOf(value), ann.value().getMask());
                }else{
                    value = LoggingHelper.markFullString(String.valueOf(value), ann.value().getMask());
                }
            }else{
                // complex type marked as hash code
                value = String.valueOf(value.hashCode());
            }
        }while(false);


        return value;
    }
}
